<template>
  <div class="createPost-container" style="position: relative">
    <el-button
      type="success"
      icon="el-icon-plus"
      @click="typeVisible = true"
      style="position: fixed; bottom: 100px; right: 50px; z-index: 9999"
      circle
    ></el-button>
    <el-form
      ref="postForm"
      v-loading="overallLoading"
      element-loading-text="拼命加载中"
      :model="postForm"
      :rules="rules"
      class="form-container"
    >
      <div
        :z-index="100"
        :class-name="'sub-navbar ' + postForm.status"
        style="
          margin-top: 50px;
          margin-left: 50px;
          display: flex;
          right: 10px;
          justify-content: space-between;
        "
      >
        <div>
          <el-cascader
            @change="choseChange"
            v-model="courseValue"
            :options="courseOptions"
            placeholder="请选择学院/年级/课程"
          ></el-cascader>
          <!-- <SourceUrlDropdown v-model="postForm.source_uri" /> -->
        </div>
        <el-button type="success" @click="explain = !explain"
          >添加作业说明</el-button
        >
      </div>

      <div class="createPost-main-container">
        <el-row>
          <!-- <Warning /> -->

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px" prop="title">
              <MDinput
                v-model="postForm.title"
                :maxlength="100"
                name="name"
                required
              >
                Title
              </MDinput>
            </el-form-item>

            <el-form-item prop="content" style="margin-bottom: 30px">
              <Tinymce
                ref="editor"
                v-if="explain"
                v-model="postForm.content"
                :height="400"
              />
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="6">
                  <el-form-item
                    label-width="80px"
                    label="任务分值:"
                    class="postInfo-container-item"
                  >
                    <el-input
                      v-model="postForm.total_points"
                      type="text"
                      placeholder="请输入任务分数"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <!-- 设置发布时间, 到时间了就会自行发布，应该就是一个倒计时，然后倒计时结束了，就是自行发布 -->
                <el-col :span="7">
                  <el-form-item
                    label-width="120px"
                    label="发布时间:"
                    class="postInfo-container-item"
                  >
                    <el-date-picker
                      v-model="postForm.publishTime"
                      type="datetime"
                      format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择开始时间"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item
                    label-width="120px"
                    label="截止时间:"
                    class="postInfo-container-item"
                  >
                    <el-date-picker
                      v-model="postForm.deadline"
                      type="datetime"
                      format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择截止时间"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <div>
          <div class="components-container board">
            <Kanban
              :key="1"
              @addOp="addOption"
              @deleteOp="deleteOption"
              @deleteQue="deleteQuestion"
              @batchAddOp="batchAddOptions"
              @batchAddQu="addQuestion"
              :list="questions"
              :group="group"
              ref="questionPaper"
              class="kanban todo"
              header-text="题卷"
            />
          </div>
        </div>

        <div style="margin: 20px auto; display: flex; justify-content: center">
          <el-button v-loading="loading" type="warning" @click="draftForm">
            存储在浏览器
          </el-button>
          <el-button
            v-loading="loading"
            style="margin-left: 50px"
            type="success"
            @click="submitForm"
          >
            发布
          </el-button>
        </div>
      </div>
    </el-form>
    <el-dialog title="请输入题目信息" :visible.sync="typeVisible" width="40%">
      <el-form>
        <el-form-item label="题目类别">
          <el-select v-model="Type" placeholder="请选择题目类别">
            <el-option
              v-for="item in optionsItem"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目数量">
          <el-input-number
            v-model="questionNum"
            controls-position="right"
            :min="1"
            :max="10"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="每题分数">
          <el-input-number
            v-model="questionScore"
            controls-position="right"
            :min="1"
            :max="10"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="typeVisible = false">取 消</el-button>
        <el-button type="primary" @click="addQuestionType">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymcecopy";
import MDinput from "@/components/MDinput";
import Sticky from "@/components/Sticky"; // 粘性header组件
import {
  CommentDropdown,
  PlatformDropdown,
  SourceUrlDropdown,
} from "./Dropdown";

import Kanban from "@/components/Question";

const defaultForm = {
  status: "draft",
  title: "", // 文章题目
  content: "", // 文章内容
  content_short: "", // 文章摘要
  source_uri: "", // 文章外链
  image_uri: "", // 文章图片
  display_time: undefined, // 前台展示时间
  id: undefined,
  platforms: false,
  comment_disabled: false,
  importance: 0,
  overallLoading: false,
};

export default {
  name: "ArticleDetail",
  components: {
    Tinymce,
    MDinput,
    Sticky,
    CommentDropdown,
    PlatformDropdown,
    SourceUrlDropdown,
    Kanban,
  },

  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === "") {
        this.$message({
          message: rule.field + "为必传项",
          type: "error",
        });
        callback(new Error(rule.field + "为必传项"));
      } else {
        callback();
      }
    };
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback();
        } else {
          this.$message({
            message: "外链url填写不正确",
            type: "error",
          });
          callback(new Error("外链url填写不正确"));
        }
      } else {
        callback();
      }
    };
    return {
      postForm: {
        total_points: "",
        publishTime: "",
        deadline: "",
        title: "",
        comment_disabled: false,
        student_correct: false,
        content: "",
        correctDeadline: "",
      },
      optionsItem: [
        {
          value: "单选题",
          label: "单选题",
        },
        {
          value: "多选题",
          label: "多选题",
        },
        {
          value: "简答题",
          label: "简答题",
        },
      ],
      explain: false,
      typeVisible: false,
      loading: false,
      userListOptions: [],
      deadline: undefined,
      publishTime: undefined,
      rules: {
        image_uri: [{ validator: validateRequire }],
        source_uri: [{ validator: validateSourceUri, trigger: "blur" }],
      },
      tempRoute: {},
      questionNum: 1,
      questionScore: 10,
      assignmentInfo: {},
      Type: "",
      questionList: [
        {
          question: "请计算圆的周长和面积",
          id: 1,
          editing: false,
          showAdd: false,
          answer: "",
          questionType: "单选题",
          proportion: "25",
          editScore: false,
          optionsList: [
            {
              content: "周长为10π， 面积为2π",
              id: 1,
              editing: false,
              isHovered: true,
            },
            {
              content: "周长为10π， 面积为5π",
              id: 2,
              editing: false,
              isHovered: true,
            },
            {
              content: "周长为10π， 面积25π",
              id: 3,
              editing: false,
              isHovered: true,
            },
            {
              content: "周长为10π， 面为25π",
              id: 4,
              editing: false,
              isHovered: true,
            },
          ],
        },
      ],
      questionType: "单选题",
      questions: {},
      group: "",
      courseOptions: [],
      courseValue: [],
      assignment: {},
    };
  },
  computed: {
    contentShortLength() {
      return this.postForm.content_short.length;
    },
    displayTime: {
      get() {
        return +new Date(this.postForm.display_time);
      },
      set(val) {
        this.postForm.display_time = new Date(val);
      },
    },
  },
  async created() {
    console.log(this.$route.params.id, "输出的是此时路由的参数");
    // let id = this.$route.params.id;
    const id = this.$route.params && this.$route.params.id;
    await this.fetchData(id);
    this.userInfo = JSON.parse(JSON.stringify(this.$store.state.user_info));
    this.tempRoute = Object.assign({}, this.$route);
    await this.getCourseData();
    console.log(this.assignment);
    this.courseValue[0] = this.assignment.institute_id;
    this.courseValue[1] = this.assignment.grade_id;
    this.courseValue[2] = this.assignment.course_id;
  },
  methods: {
    // 级联选择器改变
    choseChange() {
      console.log("此时发生了改变");
      console.log(this.courseValue);
    },
    // 查询课程信息
    async getCourseData() {
      console.log();
      let response = await this.$axios.get("/assignment/getCourseOptions", {
        params: { teacher_id: this.userInfo.teacher_id },
      });
      console.log(response);
      if (response.code == 200) {
        this.courseOptions = response.data;
      }
    },
    // 将标准时间转换为YYYY-MM-DD HH:MM:SS类型的
    formTime(time) {
      let newtime = new Date(time);
      console.log(new Date(time), "要进行转换的时间");
      const year = newtime.getFullYear();
      const month = String(newtime.getMonth() + 1).padStart(2, "0");
      const day = String(newtime.getDate()).padStart(2, "0");
      const hours = String(newtime.getHours()).padStart(2, "0");
      const minutes = String(newtime.getMinutes()).padStart(2, "0");
      const seconds = String(newtime.getSeconds()).padStart(2, "0");

      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedDate;
    },
    // 已修改
    async fetchData(id) {
      this.overallLoading = true;
      console.log();
      let response = await this.$axios.get("/assignment/fecthAssignment", {
        params: { id },
      });
      if (response.code === 200) {
        this.overallLoading = false;
        console.log(response);
        //   this.postForm = response.data;
        this.assignment = response.infoList[0];
        if (response.infoList[0].assignment_describe) {
          this.explain = true;
          this.postForm.content = response.infoList[0].assignment_describe;
        }
        this.postForm.total_points = response.infoList[0].total_points;
        this.postForm.publishTime = response.infoList[0].publish_time;
        this.postForm.deadline = response.infoList[0].deadline;
        this.postForm.title = response.infoList[0].assignment_title;
        this.postForm.comment_disabled =
          response.infoList[0].comment_disabled == "1" ? true : false;
        this.postForm.student_correct =
          response.infoList[0].student_correct == "1" ? true : false;
        if (this.postForm.student_correct) {
          this.postForm.correctDeadline = response.infoList[0].correctDeadline;
        }
        this.questions = response.infoList[0].questions;
        console.log(response.infoList[0].questions);
        console.log(this.questions);
        this.questions.singleChoiceQuestions =
          this.questions.singleChoiceQuestions.map((item) => {
            let obj = {};
            console.log(item, "item");
            obj.question_id = item.question_id;
            obj.question = item.choice_question;
            console.log(obj);
            obj.id = this.generateUniqueRandomNumber();
            obj.editing = false;
            obj.showAdd = false;
            obj.answer = JSON.parse(item.answer);
            obj.questionType = item.question_type;
            obj.proportion = item.proportion;
            obj.optionsList = JSON.parse(item.options_list);
            return obj;
          });
        this.questions.shortAnswerQuestions =
          this.questions.shortAnswerQuestions.map((item) => {
            let obj = {};
            console.log(item, "item");
            obj.question_id = item.question_id;
            obj.question = item.essayQuestion;
            obj.id = this.generateUniqueRandomNumber();
            obj.editing = false;
            obj.showAdd = false;
            obj.answer = item.answer;
            obj.questionType = item.question_type;
            obj.proportion = item.proportion;
            return obj;
          });
        this.questions.multipleChoiceQuestions =
          this.questions.multipleChoiceQuestions.map((item) => {
            let obj = {};
            console.log(item, "item");
            obj.question_id = item.question_id;
            obj.question = item.choice_question;
            obj.id = this.generateUniqueRandomNumber();
            obj.editing = false;
            obj.showAdd = false;
            obj.answer = JSON.parse(item.answer);
            obj.questionType = item.question_type;
            obj.proportion = item.proportion;
            obj.optionsList = JSON.parse(item.options_list);
            return obj;
          });
        console.log("开始执行");
        console.log(this.questions);
        console.log(this.postForm);
      }
    },
    setTagsViewTitle() {
      const title = "Edit Article";
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.postForm.id}`,
      });
      this.$store.dispatch("tagsView/updateVisitedView", route);
    },
    setPageTitle() {
      const title = "Edit Article";
      document.title = `${title} - ${this.postForm.id}`;
    },
    submitForm() {
      console.log(this.postForm);
      this.$refs.postForm.validate(async (valid) => {
        if (valid) {
          console.log(this.assignment);
          console.log(
            new Date(this.assignment.publish_time).getTime() < Date.now() &&
              new Date(this.assignment.deadline).getTime() > Date.now()
          );
          console.log(new Date(this.assignment.publish_time).getTime());
          console.log(new Date(this.assignment.deadline).getTime());
          if (
            new Date(this.assignment.publish_time).getTime() < Date.now() &&
            new Date(this.assignment.deadline).getTime() > Date.now()
          ) {
            this.$notify({
              title: "警告",
              message: "作业进行中，不能修改",
              type: "warning",
            });
          } else if(Date.now() > new Date(this.assignment.deadline).getTime()) {
            this.$notify({
              title: "警告",
              message: "作业已截止，不能修改",
              type: "warning",
            });
          } else {
            console.log(this.courseValue);
            this.postForm.institute_id = this.courseValue[0];
            this.postForm.course_id = this.courseValue[2];
            this.postForm.grade_id = this.courseValue[1];
            this.postForm.publishTime = this.formTime(
              this.postForm.publishTime
            );
            this.postForm.deadline = this.formTime(this.postForm.deadline);
            this.postForm.questions = this.questions;
            this.postForm.total_points = Number(this.postForm.total_points);
            this.postForm.teacher_id = this.userInfo.teacher_id;
            this.postForm.assignment_id = this.$route.params.id;
            this.postForm.status = "published";
            console.log(this.postForm);
            this.loading = true;
            console.log(this.$route.params.id);
            let response = await this.$axios.post(
              "/assignment/editAssignment",
              {
                data: this.postForm,
              }
            );
            if (response.code == 200) {
              this.$notify({
                title: "成功",
                message: "作业修改成功",
                type: "success",
                duration: 2000,
              });
              this.loading = false;
              this.$router.push({
                path: "/home/assignmentManage",
              });
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    draftForm() {
      if (
        this.postForm.content.length === 0 ||
        this.postForm.title.length === 0
      ) {
        this.$message({
          message: "请填写必要的标题和内容",
          type: "warning",
        });
        return;
      }
      this.$message({
        message: "保存成功",
        type: "success",
        showClose: true,
        duration: 1000,
      });
      this.postForm.status = "draft";
    },
    getRemoteUserList(query) {
      searchUser(query).then((response) => {
        if (!response.data.items) return;
        this.userListOptions = response.data.items.map((v) => v.name);
      });
    },
    // 添加选项
    addOption(data) {
      let question;

      console.log("正在执行", data.element);
      console.log(this.questions.singleChoiceQuestions[0]);
      if (data.element.questionType === "单选题") {
        question = this.questions.singleChoiceQuestions[data.index];
        let obj = {
          content: "选项" + question.optionsList.length + 1,
          id: question.optionsList.length + 1,
          editing: false,
        };
        this.questions.singleChoiceQuestions[data.index].optionsList.push(obj);
      } else if (data.element.questionType === "多选题") {
        question = this.questions.multipleChoiceQuestions[data.index];
        let obj = {
          content: "选项" + question.optionsList.length + 1,
          id: question.optionsList.length + 1,
          editing: false,
        };
        this.questions.multipleChoiceQuestions[data.index].optionsList.push(
          obj
        );
      }
      console.log(question);
      console.log(data);
    },
    // 删除选项
    deleteOption(data) {
      console.log(data);
      console.log();
      if (data.element.questionType === "单选题") {
        this.questions.singleChoiceQuestions[
          data.questionIndex
        ].optionsList.splice(data.optionsIndex, 1);
      } else if (data.element.questionType === "多选题") {
        this.questions.multipleChoiceQuestions[
          data.questionIndex
        ].optionsList.splice(data.optionsIndex, 1);
      }
    },
    // 生成随机数
    generateUniqueRandomNumber() {
      let timestamp = new Date().getTime(); // 获取当前时间戳
      let randomNumber = Math.floor(Math.random() * 1000); // 生成0到999之间的随机数
      let uniqueRandomNumber = timestamp.toString() + randomNumber.toString(); // 将时间戳和随机数拼接起来
      return parseInt(uniqueRandomNumber);
    },
    // 添加题目类型
    addQuestionType() {
      console.log(this.Type);
      let isadd;
      console.log();
      if (this.Type === "单选题") {
        isadd = this.questions.singleChoiceQuestions.length > 0;
      } else if (this.Type === "多选题") {
        isadd = this.questions.multipleChoiceQuestions.length > 0;
      } else if (this.Type === "简答题") {
        isadd = this.questions.shortAnswerQuestions.length > 0;
      }
      console.log(isadd);
      if (isadd) {
        this.$message({
          message: "该题目类型已存在",
          type: "warning",
        });
      } else {
        if (this.Type === "单选题") {
          this.questions.singleChoiceQuestions = [];
          for (let i = 0; i < this.questionNum; i++) {
            let obj = {
              question: "请选择一个选项",
              id: this.generateUniqueRandomNumber(),
              editing: true,
              showAdd: true,
              answer: "",
              questionType: "单选题",
              // 添加本题所占的比例， 让其默认是10
              proportion: this.questionScore,
              answer: "选项1",
              optionsList: [
                { content: "选项1", id: 1, editing: false, isHovered: true },
                { content: "选项2", id: 2, editing: false, isHovered: true },
              ],
            };
            this.questions.singleChoiceQuestions.push(obj);
          }
        } else if (this.Type === "多选题") {
          this.questions.multipleChoiceQuestions = [];
          console.log(this.questionNum);
          for (let i = 0; i < this.questionNum; i++) {
            let obj = {
              question: "请选择以下选项 (多选)",
              id: this.generateUniqueRandomNumber(),
              editing: true,
              showAdd: true,
              answer: "",
              // 添加本题所占的比例， 让其默认是10
              proportion: this.questionScore,
              questionType: "多选题",
              answer: '["选项2"]',
              optionsList: [
                { content: "选项1", id: 1, editing: false, isHovered: true },
                { content: "选项2", id: 2, editing: false, isHovered: true },
              ],
            };
            this.questions.multipleChoiceQuestions.push(obj);
          }
        } else if (this.Type === "简答题") {
          this.questions.shortAnswerQuestions = [];
          for (let i = 0; i < this.questionNum; i++) {
            let obj = {
              question: "请填写本项内容",
              id: this.generateUniqueRandomNumber(),
              editing: true,
              showAdd: true,
              // 添加本题所占的比例， 让其默认是10
              proportion: this.questionScore,
              questionType: "简答题",
              answer: "123",
            };
            this.questions.shortAnswerQuestions.push(obj);
          }
        }
      }
      this.typeVisible = false;
    },
    // 添加题目
    addQuestion(data) {
      console.log("执行了");
      console.log(data.questionType);
      if (data.questionType == "单选题") {
        let obj = {
          question: "请选择一个选项",
          id: this.generateUniqueRandomNumber(),
          editing: true,
          showAdd: true,
          answer: "",
          questionType: "单选题",
          // 添加本题所占的比例， 让其默认是10
          proportion: 10,
          optionsList: [
            { content: "选项1", id: 1, editing: false, isHovered: true },
            { content: "选项2", id: 2, editing: false, isHovered: true },
          ],
        };
        this.questions.singleChoiceQuestions.push(obj);
      } else if (data.questionType == "多选题") {
        let obj = {
          question: "请选择以下选项 (多选)",
          id: this.generateUniqueRandomNumber(),
          editing: true,
          showAdd: true,
          answer: "",
          // 添加本题所占的比例， 让其默认是10
          proportion: 10,
          questionType: "多选题",
          optionsList: [
            { content: "选项1", id: 1, editing: false, isHovered: true },
            { content: "选项2", id: 2, editing: false, isHovered: true },
          ],
        };
        this.questions.multipleChoiceQuestions.push(obj);
      } else if (data.questionType == "简答题") {
        let obj = {
          question: "请填写本项内容",
          id: this.generateUniqueRandomNumber(),
          editing: true,
          showAdd: true,
          // 添加本题所占的比例， 让其默认是10
          proportion: 10,
          questionType: "简答题",
          answer: "",
        };
        this.questions.shortAnswerQuestions.push(obj);
      }
      this.$refs.questionPaper.focusQuestion();
      console.log(this.questionType, "题目的种类");
    },
    // 删除题目
    deleteQuestion(data) {
      console.log(data);
      if (data.questionType === "单选题") {
        this.questions.singleChoiceQuestions.splice(data.questionIndex, 1);
      } else if (data.questionType === "多选题") {
        this.questions.multipleChoiceQuestions.splice(data.questionIndex, 1);
      } else if (data.questionType === "简答题") {
        this.questions.shortAnswerQuestions.splice(data.questionIndex, 1);
      }
    },
    // 批量添加选项
    batchAddOptions(data) {
      console.log(data);
      if (data.element.questionType === "单选题") {
        for (let i in data.optionsArr) {
          console.log(i, "i");
          let obj = {
            content: data.optionsArr[i],
            id: String(Date.now()).slice(-4) + String(Math.random()).slice(-6),
            editing: false,
            isHovered: true,
          };
          this.questions.singleChoiceQuestions[data.index].optionsList.push(
            obj
          );
        }
      } else if (data.element.questionType === "多选题") {
        for (let i in data.optionsArr) {
          console.log(i, "i");
          let obj = {
            content: data.optionsArr[i],
            id: String(Date.now()).slice(-4) + String(Math.random()).slice(-6),
            editing: false,
            isHovered: true,
          };
          this.questions.multipleChoiceQuestions[data.index].optionsList.push(
            obj
          );
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;
  z-index: 5;

  .createPost-main-container {
    padding: 20px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

.addquestion {
  display: flex;
  align-items: center;
  margin-bottom: 50px;
}
</style>
